package net.wendal.uflo.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.nutz.ioc.Ioc;
import org.nutz.ioc.Ioc2;
import org.nutz.ioc.ObjectProxy;
import org.nutz.mvc.Mvcs;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.bstek.uflo.console.UfloServlet;

public class NutUfloServlet extends UfloServlet {

    private static final long serialVersionUID = -367839499058734908L;
    
    protected String configLocation = "classpath:uflo-spring-context.xml";
    
    protected XmlWebApplicationContext applicationContext;
    
    @Override
    public void init(ServletConfig sc) throws ServletException {
        // 初始化uflo的spring环境
        applicationContext = new XmlWebApplicationContext();
        applicationContext.setServletContext(sc.getServletContext());
        applicationContext.setConfigLocation(configLocation);
        applicationContext.refresh();
        // TODO 把NutzIoc中的ProcessEventHandler注入到uflo中
        // TODO 解决CacheService,可以使用UfloEnvironmentProvider的思路
        
        // 把spring的bean,统统注入到nutz ioc
        Ioc ioc = Mvcs.ctx().getDefaultIoc();
        Ioc2 ioc2 = (Ioc2)ioc;
        for (String beanName : applicationContext.getBeanDefinitionNames()) {
            if ("uflo.props".equals(beanName))
                continue;
            if (!beanName.startsWith("uflo."))
                continue;
            ioc2.getIocContext().save("app", beanName, new ObjectProxy(applicationContext.getBean(beanName)));
        }
        super.init(sc);
    }

    protected WebApplicationContext getWebApplicationContext(ServletConfig config) {
        return applicationContext;
    }

    public void destroy() {
        super.destroy();
        applicationContext.destroy();
    }
}
